package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.SeckillFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SeckillInfoVo;
import com.atguigu.gulimall.product.vo.SkuItemSalAttrVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    private final String ZERO = "0";

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondiation(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> {
                obj.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        // 验证参数是否符合条件
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !ZERO.equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !ZERO.equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        try {
            String max = (String) params.get("max");
            BigDecimal bigDecimal = new BigDecimal(max);
            // 大于返回1 小于返回 -1
            if (bigDecimal.compareTo(new BigDecimal("0")) == 1) {
                wrapper.le("price", max);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = this.list(new QueryWrapper<SkuInfoEntity>()
                .eq("spu_id", spuId));
        return skuInfoEntities;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        /**
         * Completable:
         *      thenAcceptAsync：异步方式消费结果,无返回
         *      runAsync：异步执行,无返回结果
         *      allOf：等待所有任务完成
         */
        // 1.1、获取sku信息 pms_sku_info
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity skuInfoEntity = getById(skuId);
            skuItemVo.setSkuInfo(skuInfoEntity);
            return skuInfoEntity;
        });
        // 2、获取spu销售属性组合
        CompletableFuture<Void> saleFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            List<SkuItemSalAttrVo> salAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(salAttrVos);
        });
        // 3、获取spu的介绍
        CompletableFuture<Void> InfoDescFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity spuInfoDescServiceById = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescServiceById);
        });
        // 4、获取spu的规格参数信息 
        CompletableFuture<Void> attrGroupFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        });
        // 5、获取 sku图片信息 pms_sku_images
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> skuImagesEntityList = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(skuImagesEntityList);
        });
        // 6、查询商品是否参加秒杀
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            // 远程请求秒杀服务，查看该商品是否参加过秒杀
            R sKuSeckillInfo = seckillFeignService.getSKuSeckillInfo(skuId);
            if (sKuSeckillInfo.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = sKuSeckillInfo.getData(new TypeReference<SeckillInfoVo>() {
                });
                skuItemVo.setSeckillInfoVo(seckillInfoVo);
            }
        }, executor);


        // 6、等待所有任务完成
        CompletableFuture.allOf(saleFuture, InfoDescFuture, attrGroupFuture, imageFuture, seckillFuture).get();
        return skuItemVo;
    }
}